<?php
namespace app\install\controller;

/**
 * 主框架安装模块
 * @author Lain
 *
 */

use think\Controller;
use think\Request;

class Index  extends Controller{

	private $errormsg;
    public $connect;

	/**
	 * [_initialize 初始化]
	 * @return [type] [description]
	 */
	public function _initialize()
	{
        if(is_file(APP_PATH.'/install/install.lock'))
           exception('请先删除Intall目录下面install.lock文件');
        
        define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
        define('IS_POST',       REQUEST_METHOD =='POST' ? true : false);
	}

	/**
	 * [index 欢迎方法]
	 * @return [type] [description]
	 */
    public function index()
    {
        session('step',false);
		return $this->fetch();
    }


    /**
     * [step1 检查环境和目录权限]
     * @return [type] [description]
     */
    public function step1()
    {

        session('step',false);
    	// 需要可以读写的目录
    	$dir = array(
    		//array('name'=>'./ThinkPHP','text'=>'主程序','status'=>0),
    		array('name'=>'../runtime','text'=>'配置文件、数据、缓存','status'=>0),
    	);

    	foreach ($dir as $k=> $v) 
    	{
    		if(is_writable($v['name'])) $dir[$k]['status']=1;
    	}
    	$this->assign('dir',$dir);


    	// 环境
    	$method = array(
    		array('name'=>'mbsring扩展','function'=>'mb_substr','text'=>'字符串处理','status'=>0),
    		array('name'=>'gd库','function'=>'imagecopy','text'=>'图像处理','status'=>0),
    	);
    	foreach ($method as $k=> $v) 
    	{
    		if(function_exists($v['function'])) $method[$k]['status']=1;
    	}
		$this->assign('method',$method);

    	return $this->fetch();
    }




    /**
     * [step2 第二步 设置数据库链接和后台管理员账号]
     * @return [type] [description]
     */
    public function step2()
    {
    	if(IS_POST)
    	{
    		echo $this->fetch('create_table');
    		// 执行验证
    		if(!$this->_verify()) $this->error($this->errormsg);
            session('step', true);
    		// 执行写入配置文件
    		$this->_write_config();
    		// 执行sql文件
    		$this->_sql_query();
    		// 创建用户
    		$this->_add_user();
            mysqli_close($this->connect);
            
    		// 跳转
            echo "<script type=\"text/javascript\">setTimeout(function(){location.href='".url('Index/step3')."'},5000)</script>";
            ob_flush();
            flush();
    	}else{
    		session('step', false);
    		return $this->fetch();
    	}
    }


    /**
     * [step3 第三步设置lock文件，提示系统安装成功]
     * @return [type] [description]
     */
    public function step3()
    {   
        if(!session('step'))
            $this->redirect('Index/index');
        // 创建文件
        file_put_contents(APP_PATH.'/install/install.lock', '');
    	return $this->fetch();
    }



    /**
     * [ajaxcheck ajax验证数据库链接是否正常]
     * @return [type] [description]
     */
    public function ajaxcheck()
    {
    	$data['dblink'] = input('post.dblink');
    	$data['dbuser'] = input('post.dbuser');
        $data['dbpassword'] = input('post.dbpassword');
    	$data['dbport'] = input('post.dbport');
        //dump($data);die;

    	if($this->_checkdb($data))
    		echo 1;
    	else
    		echo 0;
    	die;
    }

   
    /*********************************验证******************************************/


    private function  _verify()
    {
        // 验证必填
        $dblink = input('post.dblink');
        $dbname = input('post.dbname');
        $dbprefix =input('post.dbprefix');
        $dbuser = input('post.dbuser');
        $dbpassword = input('post.dbpassword');

        $username = input('post.username');
        $nickname = input('post.nickname');
        $password = input('post.password');
        $email = input('post.email');


        // 数据库链接信息验证
        if(!$dblink)
        {
            $this->errormsg='请输入数据库链接地址';
            return false;
        }
        if(!$dbname)
        {
            $this->errormsg='请输入数据库名称';
            return false;
        }
        if(!$dbprefix)
        {
            $this->errormsg='请输入数据库表前缀';
            return false;
        }
        if(!$dbuser)
        {
            $this->errormsg='请输入数据库用户名';
            return false;
        }
        if(!$this->_dbpassword())
        {
            $this->errormsg='数据库密码不正确';
            return false;
        }

        // 管理员账号验证
        if(!$username)
        {
            $this->errormsg='请输入管理员账号';
            return false;
        }

        if(!$username)
        {
            $this->errormsg='请输入管理员账号';
            return false;
        }


        if(!$nickname)
        {
            $this->errormsg='请输入管理员昵称';
            return false;
        }
        if(!$email)
        {
            $this->errormsg='请输入管理员邮箱';
            return false;
        }

        if(!preg_match('/^([a-zA-Z0-9_\-\.])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/i', $email))
        {
            $this->errormsg='邮箱格式不正确';
            return false;
        }
        

       
   
       return true;
    }


    /**
     * [_dbpassword 检查数据库连接]
     * @return [type] [description]
     */
    private function _dbpassword()
    {
        $data['dblink'] = input('post.dblink');
        $data['dbuser'] = input('post.dbuser');
        $data['dbpassword'] = input('post.dbpassword');
        $data['dbport'] = input('post.dbport');

        // 执行验证
        if($this->_checkdb($data))
            return true;
        else
            return false;
    }



     /**
     * [_checkdb 验证数据链接]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    private function _checkdb($data){
        try{
            mysqli_connect($data['dblink'],$data['dbuser'],$data['dbpassword'], '', $data['dbport']);
        }catch(\Exception $e){
            return false;
        }
        return true;
        // if(mysqli_connect($data['dblink'],$data['dbuser'],$data['dbpassword']))
        //     return true;
        // else
        //     return false;
    }

    /**
     * [_write_config 写配置文件]
     * @return [type] [description]
     */
    private function _write_config()
    {

        $dbuser = input('post.dbuser');
        $dbpassword = input('post.dbpassword');
        $dblink = input('post.dblink');
        $dbname = input('post.dbname');
        $dbport = input('post.dbport');

        $data['type']       = 'mysql';
        $data['hostname']   = $dblink;
        $data['database']   = $dbname;
        $data['username']   = $dbuser;
        $data['password']   = $dbpassword;
        $data['hostport']   = $dbport ? $dbport : '3306';
        $data['prefix']     = input('post.dbprefix');
        $data['charset']    = 'utf8';
// var_dump($data);exit;
        $config = var_export($data,true);
        $time = date('Y-m-d H:i:s');
        $php =<<<str
<?php
/**[数据配置文件]
 * @Author: 165490077@qq.com
 * @Date:   $time
 * @Last Modified by:   Lain
 * @Last Modified time: $time
 */
return $config;
str;
        //写入文件
        $result = file_put_contents('../application/database.php', $php);
        //连接数据库
        $this->connect = mysqli_connect($dblink, $dbuser, $dbpassword, $dbname, $dbport);
        mysqli_set_charset($this->connect, "utf8");
        return true;
    }


    /**
     * [_sql_query 执行sql文件]
     * @return [type] [description]
     */
    private function _sql_query()
    {
        $installdata = input('post.installdata');
        $dbname = input('post.dbname');
        // 创建数据库
        // mysql_query("CREATE DATABASE IF NOT EXISTS `".$dbname."` default   charset   utf8;");
        // 选择数据库
        // mysql_select_db($dbname);
        // 设置编码
        // mysql_query("set names utf8");

        // 表前缀
        $dbPrefix=input('post.dbprefix');
        $sql = file_get_contents('../db_thinkphp5+bjui.sql');
        $sql = str_replace("\r", "\n", $sql);
        $sql = explode(";\n", $sql);
        //$orginal = C('ORIGINAL_TABLE_PREFIX');
        $sql = str_replace(" `db_", " `{$dbPrefix}", $sql);
        
        
        //开始安装
        show_msg('开始安装数据库...');
        foreach ($sql as $value) {
        	$value = trim($value);
        	if (empty($value)) continue;
        	if (substr($value, 0, 12) == 'CREATE TABLE') {
        		$name = preg_replace("/^CREATE TABLE `(\w+)` .*/s", "\\1", $value);
        		$msg = "创建数据表{$name}";
        		if (false !== mysqli_query($this->connect, $value)) {
        			show_msg($msg . '...成功');
        		} else {
        			show_msg($msg . '...失败');
        		}
        	} else {
        		mysqli_query($this->connect, $value);
        	}
        }
        // die;
        return true;
    }



    /**
     * [_add_user 添加用户]
     */
    private function _add_user()
    {
        // 管理员账号
        $username = input('post.username');
        // 管理员昵称
        $nickname = input('post.nickname');
        // 登录密码
        $password = hash_hmac('sha256',input('post.password'), $username);
        // 邮箱
        $email = input('post.email');
        // 表前缀
        $dbPrefix = input('post.dbprefix');
        // 组合sql
        $sql="INSERT INTO `{$dbPrefix}admin`(userid,username,password,roleid,nickname,email,`status`) VALUES (1, '{$username}', '{$password}', '1', '{$nickname}', '{$email}',  1)";
        
        // 执行插入
        mysqli_query($this->connect, $sql);

        return true;
    }

	}